local lingji = fk.CreateSkill{
  name = "th_lingji",
  max_branches_use_time = {
    ["spade"] = {
      [Player.HistoryRound] = 1
    },
    ["heart"] = {
      [Player.HistoryRound] = 1
    },
    ["club"] = {
      [Player.HistoryRound] = 1
    },
    ["diamond"] = {
      [Player.HistoryRound] = 1
    },
  }
}

lingji:addEffect("viewas", {
  pattern = "slash,jink",
  prompt = "#th_lingji",
  mute_card = false,
  handly_pile = true,
  interaction = function(self, player)
    local all_names = { "slash", "jink" }
    local names = player:getViewAsCardNames(lingji.name, all_names)
    return UI.CardNameBox { choices = names, all_choices = all_names }
  end,
  filter_pattern = function(self, player, card_name, selected)
    local suits = {}
    for _, suit in ipairs({ "spade", "heart", "club", "diamond" }) do
      if lingji:withinBranchTimesLimit(player, suit, Player.HistoryRound) then
        table.insert(suits, suit)
      end
    end
    return {
      min_num = 1,
      max_num = 1,
      pattern = ".|.|" .. table.concat(suits, ",")
    }
  end,
  view_as = function(self, player, cards)
    if #cards ~= 1 or self.interaction.data == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = lingji.name
    card:addSubcard(cards[1])
    return card
  end,
  history_branch = function (self, player, data)
    if #(data.cards or {}) ~= 0 then
      return Fk:getCardById(data.cards[1]):getSuitString()
    end
  end,
  enabled_at_play = function(self, player)
    return not player:isNude()
  end,
  enabled_at_response = function(self, player, cardResponsing)
    return not player:isNude()
  end,
}, { check_skill_limit = true })
local th_lingji_record = { ---@type TrigSkelSpec<fun(self: TriggerSkill, event: UseCardEvent, target: ServerPlayer, player: ServerPlayer, data: UseCardData):any>
  mute = true,
  can_refresh = function(self, event, target, player, data)
    return target == player and data.card and table.contains(data.card.skillNames, "th_lingji")
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local suits = player:getTableMark("@[suits]th_lingji-round-noclear")
    table.insertIfNeed(suits, data.card.suit)
    room:setPlayerMark(player, "@[suits]th_lingji-round-noclear", suits)
    room.logic:getCurrentEvent():addExitFunc(function()
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(player, false)) do
        if not p:isNude() then
          table.insert(targets, p)
        end
      end
      local to = room:askToChoosePlayers(player, {
        targets = targets,
        min_num = 1,
        max_num = 1,
        prompt = "#th_lingji-discard",
        skill_name = lingji.name,
        cancelable = true
      })
      if #to == 1 then
        local tar = to[1]
        local card = room:askToChooseCard(player, {
          target = tar,
          flag = "hej",
          skill_name = lingji.name
        })
        if card then
          room:throwCard(card, lingji.name, tar, player)
        end
      end
    end)
  end,
}
lingji:addEffect(fk.PreCardUse, th_lingji_record)
lingji:addEffect(fk.PreCardRespond, th_lingji_record)

lingji:addTest(function(room, me)
  FkTest.RunAddSkills(me, lingji.name)

  local comp2, comp3 = room.players[2], room.players[3]
  local slashD = room:printCard("slash", Card.Diamond, 13)
  local jinkC = room:printCard("jink", Card.Club, 1)
  local peachS = room:printCard("peach", Card.Spade, 1)
  local analepticH = room:printCard("analeptic", Card.Heart, 13)
  local duelH = room:printCard("duel", Card.Heart, 13)
  local slash = Fk:getCardById(1)

  -- test1: 第一个出牌阶段内：用灵击对comp2使用杀(红桃酒)
  -- 期望：第一次使用牌询问可以选择五张牌
  FkTest.setRoomBreakpoint(me, "PlayCard")

  -- test2: 发动后续效果
  -- 期望：只有comp3（提前摸一张牌）可选
  FkTest.setRoomBreakpoint(me, "AskForUseActiveSkill", function(data)
    return data[1] == "choose_players_skill" and data[4] and
      data[4].skillName == lingji.name
  end)

  -- test3: 在comp2的回合对me使用杀，检测闪的使用条件
  -- 期望：可以选择三张牌（红桃决斗不可选择）
  FkTest.setRoomBreakpoint(me, "AskForUseCard", function(data)
    return Fk.currentResponsePattern == "jink"
  end)

  FkTest.runInRoom(function()
    room:obtainCard(me, { slashD, jinkC, peachS, analepticH, duelH })
    comp3:drawCards(1)
    GameEvent.Round:create():exec()
  end)

  -- test1: 用灵击对comp2使用杀(红桃酒)
  local handler = ClientInstance.current_request_handler --[[@as ReqPlayCard]]
  lu.assertIsTrue(handler:skillButtonValidity(lingji.name))
  handler:selectSkill(lingji.name, { selected = true })
  lu.assertEquals(Fk.skills[lingji.name].interaction.data, "slash")
  for _, cid in ipairs(me:getCardIds("h")) do
    lu.assertIsTrue(handler:cardValidity(cid))
  end
  FkTest.runInClient(function()
    handler:selectCard(analepticH.id, { selected = true })
  end)
  for _, cid in ipairs(me:getCardIds("h")) do
    lu.assertIsFalse(handler:cardValidity(cid))
  end
  FkTest.setNextReplies(me, {
    json.encode {
      card = { skill = lingji.name, subcards = { analepticH.id } },
      targets = { comp2.id },
      interaction_data = "slash"
    }
  })
  FkTest.resumeRoom()

  -- test2: 发动后续效果
  local handler2 = ClientInstance.current_request_handler --[[@as ReqActiveSkill]]
  for _, target in ipairs(room:getOtherPlayers(me, false)) do
    if target == comp3 then
      lu.assertIsTrue(handler2:targetValidity(target.id))
    else
      lu.assertIsFalse(handler2:targetValidity(target.id))
    end
  end
  FkTest.setNextReplies(me, {
    FkTest.replyChoosePlayer({ comp3 })
  })

  -- test3: 在comp2的回合对me使用杀，检测闪的使用条件
  FkTest.setNextReplies(comp2, {
    FkTest.replyCard(slash, { me })
  })
  FkTest.resumeRoom()

  local handler3 = ClientInstance.current_request_handler --[[@as ReqUseCard]]
  lu.assertIsTrue(handler3:skillButtonValidity(lingji.name))
  handler3:selectSkill(lingji.name, { selected = true })
  lu.assertEquals(Fk.skills[lingji.name].interaction.data, "jink")
  for _, cid in ipairs(me:getCardIds("h")) do
    if cid == duelH.id then
      lu.assertIsFalse(handler3:cardValidity(cid))
    else
      lu.assertIsTrue(handler3:cardValidity(cid))
    end
  end
  FkTest.setNextReplies(me, {
    json.encode {
      card = { skill = lingji.name, subcards = { jinkC.id } },
      interaction_data = "jink"
    },
    FkTest.replyChoosePlayer({ comp2 })
  })
  FkTest.resumeRoom()
end)

Fk:loadTranslationTable{
  ["th_lingji"] = "灵击",
  [":th_lingji"] ="每轮每种花色限一次，你可以将一张牌当【杀】或【闪】使用或打出，然后你可以弃置一名其他角色区域内一张牌。",

  ["#th_lingji"] ="灵击：将一张牌当【杀】或【闪】使用或打出，然后你可以弃置一名其他角色区域内一张牌",

  ["#th_lingji-discard"] = "灵击：你可以弃置一名其他角色区域内一张牌",

  ["@[suits]th_lingji-round-noclear"] = "灵击",
}

return lingji
